define(['jquery', 'bootstrap', 'backend', 'table', 'form', 'layer'], function ($, undefined, Backend, Table, Form, Layer) {

    var Controller = {
        index: function () {
            // 获取后端传递的语言包数据
            var lang = Config.lang || {};

            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'communityclasses/communityclasses/index',
                    add_url: 'communityclasses/communityclasses/add',
                    edit_url: 'communityclasses/communityclasses/edit',
                    del_url: 'communityclasses/communityclasses/del',
                    multi_url: 'communityclasses/communityclasses/multi',
                    table: 'ocation_class',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'sequence_number',
                sortOrder: 'asc',
                columns: [
                    [
                        { checkbox: true },
                        { field: 'id', title: lang['Id'] || __('Id'), visible: false },
                        {
                            field: 'sequence_number', title: lang['Class Number'] || '班级序号', sortable: true, formatter: function (value, row) {
                                if (row.formatted_sequence) {
                                    return '<span class="text-primary font-weight-bold">' + row.formatted_sequence + '</span>';
                                }
                                return '';
                            }
                        },
                        { field: 'name', title: lang['Class Name'] || '班级名称' },
                        { field: 'ocation_name', title: lang['Teaching Point Name'] || '教学点名称' },
                        {
                            field: 'manager_id', title: lang['Manager ID'] || '管理员ID', formatter: function (value, row) {
                                return value > 0 ? '<span class="text-success">' + value + '</span>' : '<span class="text-muted">' + (lang['None'] || '无') + '</span>';
                            }
                        },
                        {
                            field: 'open_apply', title: lang['Open Application'] || '开放申请', formatter: function (value, row) {
                                return value == 1 ? '<span class="text-success">' + (lang['Yes'] || '是') + '</span>' : '<span class="text-danger">' + (lang['No'] || '否') + '</span>';
                            }
                        },
                        {
                            field: 'show_in_team_list', title: lang['Show in Team List'] || '团队列表显示', formatter: function (value, row) {
                                return value == 1 ? '<span class="text-success">' + (lang['Yes'] || '是') + '</span>' : '<span class="text-danger">' + (lang['No'] || '否') + '</span>';
                            }
                        },
                        { field: 'cover', title: lang['Class Avatar'] || '班级头像', formatter: Table.api.formatter.image },
                        { field: 'create_time', title: lang['Create Time'] || '创建时间', formatter: Table.api.formatter.datetime },
                        { field: 'operate', title: lang['Operate'] || '操作', table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
            // 先加载通用脚本
            var script = document.createElement('script');
            script.src = '/assets/js/backend/common/add.js?v=' + new Date().getTime();
            document.head.appendChild(script);

            // 等待通用脚本加载完成后再执行初始化
            script.onload = function () {
                // 延迟执行，确保通用脚本的事件绑定完成
                setTimeout(function () {
                    // 触发教学点数据加载（使用通用脚本的逻辑）
                    if ($('#c-ocation_id').length > 0) {
                        $('#c-ocation_id').trigger('change2');
                    }

                    // 触发社区数据加载（使用通用脚本的逻辑）
                    if ($('#c-community_id').length > 0) {
                        $('#c-community_id').trigger('change2');
                    }
                }, 100);
            };

            Controller.api.bindevent();

            // 教学点选择变化时自动生成班级名称
            $(document).on('change', '#c-ocation_id', function () {
                var selectedOption = $(this).find('option:selected');
                var ocationName = selectedOption.text();
                if (ocationName && ocationName !== '请选择教学点' && ocationName !== '') {
                    $('#c-name').val(ocationName + '班');
                }
            });

        },
        edit: function () {
            // 先加载通用脚本
            var script = document.createElement('script');
            script.src = '/assets/js/backend/common/add.js?v=' + new Date().getTime();
            document.head.appendChild(script);
            Controller.api.bindevent();

            // 初始化班级成员管理
            Controller.api.initClassMembers();
            
            // 初始化管理员选择功能
            Controller.api.initManagerSelection();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            },

            loadCommunities: function () {
                // 加载社区数据
                if ($('#c-community_id').length > 0) {
                    $.ajax({
                        url: '/ocation/ocation/getCommunityList',
                        type: 'GET',
                        success: function (data) {
                            var $select = $('#c-community_id');
                            var currentValue = $select.data('value');
                            $select.empty().append('<option value="">请选择</option>');

                            if (data && data.length > 0) {
                                $.each(data, function (index, item) {
                                    var selected = (currentValue == item.id) ? 'selected' : '';
                                    $select.append('<option value="' + item.id + '" ' + selected + '>' + item.name + '</option>');
                                });
                            }
                            $select.selectpicker('refresh');
                        }
                    });
                }
            },

            loadOcations: function () {
                // 加载教学点数据
                if ($('#c-ocation_id_sq').length > 0) {
                    $.ajax({
                        url: '/ocation/ocation/lists2',
                        type: 'GET',
                        data: {
                            cityId: Config.admin ? Config.admin.city_id : '',
                            relType: Config.admin ? Config.admin.rel_type : '',
                            relId: Config.admin ? Config.admin.rel_id : ''
                        },
                        success: function (data) {
                            var $select = $('#c-ocation_id_sq');
                            var currentValue = $select.data('value');
                            $select.empty().append('<option value="">请选择</option>');

                            if (data && typeof data === 'string') {
                                data = JSON.parse(data);
                            }

                            if (data && data.list && data.list.length > 0) {
                                $.each(data.list, function (index, item) {
                                    var selected = (currentValue == item.id) ? 'selected' : '';
                                    $select.append('<option value="' + item.id + '" ' + selected + '>' + item.name + '</option>');
                                });
                            }
                        }
                    });
                }
            },

            initClassMembers: function () {
                // 获取当前班级ID
                var rowData = $('#row').val();
                var classId = '';
                if (rowData) {
                    try {
                        var row = JSON.parse(rowData);
                        classId = row.id;
                    } catch (e) {
                        console.error('解析班级数据失败:', e);
                        return;
                    }
                }

                if (!classId) {
                    console.error('未找到班级ID');
                    return;
                }

                // 初始化成员表格
                var $membersTable = $('#members-table');
                if ($membersTable.length > 0) {
                    var membersUrl = Fast.api.fixurl('communityclasses/communityclasses/getClassMembers') + '?class_id=' + classId + '&classes_type=2';

                    $membersTable.bootstrapTable('destroy');
                    $membersTable.bootstrapTable({
                        url: membersUrl,
                        method: 'get',
                        dataType: 'json',
                        pagination: true,
                        sidePagination: 'server',
                        pageSize: 10,
                        pageList: [10, 25, 50, 100],
                        search: true,
                        showRefresh: true,
                        showToggle: true,
                        showColumns: true,
                        sortName: 'create_time',
                        sortOrder: 'desc',
                        columns: [
                            { field: 'state', checkbox: true },
                            { field: 'id', title: 'ID', visible: false },
                            { field: 'student_id', title: '学员ID', sortable: true },
                            { field: 'username', title: '用户名', sortable: true },
                            { field: 'nickname', title: '昵称', sortable: true },
                            { field: 'mobile', title: '手机号', sortable: true },
                            {
                                field: 'status',
                                title: '状态',
                                sortable: true,
                                formatter: function (value) {
                                    var statusMap = {
                                        '0': '<span class="label label-warning">待审批</span>',
                                        '1': '<span class="label label-success">正常</span>',
                                        '2': '<span class="label label-danger">已拒绝</span>'
                                    };
                                    return statusMap[value] || '<span class="label label-default">未知</span>';
                                }
                            },
                            {
                                field: 'create_time',
                                title: '加入时间',
                                sortable: true,
                                formatter: function (value) {
                                    return value ? new Date(value).toLocaleString() : '';
                                }
                            },
                            {
                                field: 'operate',
                                title: '操作',
                                formatter: function (value, row) {
                                    var html = [];
                                    html.push('<a href="javascript:;" class="btn btn-xs btn-primary btn-edit-member" data-id="' + row.id + '">编辑</a>');
                                    html.push('<a href="javascript:;" class="btn btn-xs btn-danger btn-remove-member" data-id="' + row.id + '">删除</a>');
                                    return html.join(' ');
                                },
                                events: {
                                    'click .btn-edit-member': function (e, value, row) {
                                        Controller.api.editMember(row);
                                    },
                                    'click .btn-remove-member': function (e, value, row) {
                                        Controller.api.removeMember([row.id]);
                                    }
                                }
                            }
                        ]
                    });

                    // 添加错误处理
                    $membersTable.on('load-error.bs.table', function (e, status) {
                        console.error('表格加载错误:', status);
                        Layer.msg('加载成员列表失败，请检查网络连接', { icon: 2, time: 3000 });
                    });

                    // 添加成功加载处理
                    $membersTable.on('load-success.bs.table', function (e, data) {
                        Controller.api.updateMemberStats(data);
                    });
                }

                // 绑定按钮事件
                $('#btn-add-member').on('click', function () {
                    Controller.api.showAddMemberDialog(classId);
                });

                $('#btn-remove-member').on('click', function () {
                    var selections = $membersTable.bootstrapTable('getSelections');
                    if (selections.length === 0) {
                        Layer.msg('请选择要删除的成员', { icon: 0 });
                        return;
                    }
                    var ids = selections.map(function (item) { return item.id; });
                    Controller.api.removeMember(ids);
                });

                $('#btn-approve-member').on('click', function () {
                    var selections = $membersTable.bootstrapTable('getSelections');
                    if (selections.length === 0) {
                        Layer.msg('请选择要审批的成员', { icon: 0 });
                        return;
                    }
                    var ids = selections.map(function (item) { return item.id; });
                    Controller.api.approveMember(ids);
                });

                // 绑定刷新按钮事件
                $('#btn-refresh-members').on('click', function () {
                    Layer.msg('正在刷新成员列表...', { icon: 16, time: 1000 });
                    $membersTable.bootstrapTable('refresh');
                });

                // 绑定导出按钮事件
                $('#btn-export-members').on('click', function () {
                    Controller.api.exportMembers(classId);
                });

                // 监听选项卡切换事件，刷新成员列表
                $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
                    if ($(e.target).attr('href') === '#class-members') {
                        $membersTable.bootstrapTable('refresh');
                    }
                });

                // 注意：load-success事件已在表格初始化时绑定，这里不需要重复绑定
            },

            showAddMemberDialog: function (classId) {
                var html = `
                    <div style="padding: 20px;">
                        <div class="form-group" style="margin-bottom: 20px;">
                            <label class="control-label" style="font-weight: bold; margin-bottom: 8px; display: block;">
                                <i class="fa fa-search"></i> 搜索用户：
                            </label>
                            <div class="input-group">
                                <input type="text" id="search-user" class="form-control" 
                                       placeholder="输入用户名、昵称或手机号进行搜索" 
                                       style="border-radius: 4px 0 0 4px;">
                                <span class="input-group-btn">
                                    <button type="button" id="btn-search-user" class="btn btn-primary" 
                                            style="border-radius: 0 4px 4px 0;">
                                        <i class="fa fa-search"></i> 搜索
                                    </button>
                                    <button type="button" id="btn-load-all" class="btn btn-default" 
                                            title="显示所有用户">
                                        <i class="fa fa-list"></i> 全部
                                    </button>
                                </span>
                            </div>
                            <small class="help-block text-muted">
                                <i class="fa fa-info-circle"></i> 提示：留空搜索框点击"全部"可显示所有用户
                            </small>
                        </div>
                        
                        <div class="form-group" style="margin-bottom: 20px;">
                            <label class="control-label" style="font-weight: bold; margin-bottom: 8px; display: block;">
                                <i class="fa fa-user"></i> 选择用户：
                            </label>
                            <div id="user-list-container" style="max-height: 200px; overflow-y: auto; border: 1px solid #ddd; border-radius: 4px; background: #f9f9f9;">
                                <div id="user-loading" style="padding: 20px; text-align: center; color: #999;">
                                    <i class="fa fa-spinner fa-spin"></i> 正在加载用户列表...
                                </div>
                            </div>
                            <input type="hidden" id="selected-user-id" value="">
                            <div id="selected-user-info" style="margin-top: 8px; padding: 8px; background: #e8f5e8; border-radius: 4px; display: none;">
                                <strong>已选择：</strong><span id="selected-user-text"></span>
                            </div>
                            <small class="help-block text-muted">
                                <i class="fa fa-info-circle"></i> 点击用户头像或名称进行选择
                            </small>
                        </div>
                        
                        <div class="form-group" style="margin-bottom: 15px;">
                            <label class="control-label" style="font-weight: bold; margin-bottom: 8px; display: block;">
                                <i class="fa fa-flag"></i> 初始状态：
                            </label>
                            <select id="member-status" class="form-control" style="border-radius: 4px;">
                                <option value="1">✓ 正常 (直接加入班级)</option>
                                <option value="0">⏳ 待审批 (需要管理员审核)</option>
                            </select>
                        </div>
                        
                        <div class="alert alert-info" style="margin-top: 15px; padding: 10px; border-radius: 4px;">
                            <i class="fa fa-lightbulb-o"></i> 
                            <strong>操作提示：</strong>选择用户后点击确定即可添加到班级中
                        </div>
                    </div>
                `;

                Layer.open({
                    type: 1,
                    title: '<i class="fa fa-user-plus"></i> 添加班级成员',
                    content: html,
                    area: ['600px', '500px'],
                    btn: ['<i class="fa fa-check"></i> 确定添加', '<i class="fa fa-times"></i> 取消'],
                    btnAlign: 'c',
                    success: function (layero, index) {
                        // 对话框显示成功后立即加载用户列表
                        setTimeout(function () {
                            loadUsers('');
                        }, 100);

                        // 绑定搜索按钮事件
                        $('#btn-search-user').on('click', function () {
                            var keyword = $('#search-user').val().trim();
                            loadUsers(keyword);
                        });

                        // 绑定显示全部按钮事件
                        $('#btn-load-all').on('click', function () {
                            $('#search-user').val('');
                            loadUsers('');
                        });

                        // 绑定回车搜索
                        $('#search-user').on('keypress', function (e) {
                            if (e.which === 13) {
                                var keyword = $(this).val().trim();
                                loadUsers(keyword);
                            }
                        });

                        // 绑定双击选择用户
                        $(document).on('dblclick', '#select-user option', function () {
                            $(this).prop('selected', true);
                        });
                    },
                    yes: function (index, layero) {
                        var studentId = $('#selected-user-id').val();
                        var status = $('#member-status').val();
                        var selectedText = $('#selected-user-text').text();

                        if (!studentId) {
                            Layer.msg('请先选择要添加的用户', {
                                icon: 0,
                                time: 2000,
                                shade: 0.3
                            });
                            return false;
                        }

                        // 显示加载状态
                        Layer.msg('正在添加成员...', {
                            icon: 16,
                            shade: 0.3,
                            time: 0
                        });

                        $.ajax({
                            url: '/communityclasses/communityclasses/addClassMember',
                            type: 'POST',
                            data: {
                                class_id: classId,
                                student_id: studentId,
                                status: status
                            },
                            success: function (data) {
                                Layer.closeAll('loading');
                                if (data.code === 1) {
                                    Layer.msg('成功添加用户：' + selectedText, {
                                        icon: 1,
                                        time: 2000
                                    });
                                    $('#members-table').bootstrapTable('refresh');
                                    Layer.close(index);
                                } else {
                                    Layer.msg(data.msg || '添加失败', {
                                        icon: 2,
                                        time: 3000
                                    });
                                }
                            },
                            error: function () {
                                Layer.closeAll('loading');
                                Layer.msg('网络错误，请重试', {
                                    icon: 2,
                                    time: 3000
                                });
                            }
                        });

                        return false; // 阻止默认关闭
                    }
                });

                // 加载用户列表的函数
                function loadUsers(keyword) {
                    keyword = keyword || '';

                    var $container = $('#user-list-container');
                    $container.html('<div style="padding: 20px; text-align: center; color: #999;"><i class="fa fa-spinner fa-spin"></i> 正在搜索用户...</div>');

                    $.ajax({
                        url: '/communityclasses/communityclasses/searchUsers',
                        type: 'GET',
                        data: { q: keyword },
                        success: function (data) {
                            $container.empty();
                            
                            // 保存管理员列表到全局变量，供选择头像使用
                            if (data.code === 1 && data.data) {
                                window.currentAdminList = data.data;
                            }
                            
                            // 保存管理员列表到全局变量，供选择头像使用
                            if (data.code === 1 && data.data) {
                                window.currentAdminList = data.data;
                            }

                            if (data.code === 1 && data.data && data.data.length > 0) {
                                // 添加提示信息
                                var tipText = keyword ?
                                    '搜索到 ' + data.total + ' 个用户' :
                                    '共 ' + data.total + ' 个用户';
                                $container.append('<div style="padding: 8px; background: #e8f4fd; border-bottom: 1px solid #ddd; font-size: 12px; color: #666;"><i class="fa fa-info-circle"></i> ' + tipText + '</div>');

                                // 添加用户列表
                                $.each(data.data, function (index, user) {
                                    var displayName = user.nickname || user.username || '未知用户';
                                    var username = user.username || 'ID:' + user.id;
                                    var mobile = user.mobile ? ' | ' + user.mobile : '';

                                    // 构建头像URL
                                    var avatarUrl = user.avatar || '/assets/img/avatar.png';
                                    if (avatarUrl && !avatarUrl.startsWith('http') && !avatarUrl.startsWith('/')) {
                                        avatarUrl = '/' + avatarUrl;
                                    }

                                    // 创建默认头像元素
                                    var avatarElement = '';
                                    if (user.avatar && user.avatar_type !== 'default') {
                                        avatarElement = `<img src="${avatarUrl}" alt="头像" 
                                                         style="width: 32px; height: 32px; border-radius: 50%; margin-right: 10px; border: 1px solid #ddd; object-fit: cover;"
                                                         onerror="this.style.display='none'; this.nextElementSibling.style.display='flex';">
                                                         <div style="width: 32px; height: 32px; border-radius: 50%; margin-right: 10px; border: 1px solid #ddd; background: #f0f0f0; display: none; align-items: center; justify-content: center; color: #999; font-size: 14px;">
                                                             <i class="fa fa-user"></i>
                                                         </div>`;
                                    } else {
                                        avatarElement = `<div style="width: 32px; height: 32px; border-radius: 50%; margin-right: 10px; border: 1px solid #ddd; background: #f0f0f0; display: flex; align-items: center; justify-content: center; color: #999; font-size: 14px;">
                                                             <i class="fa fa-user"></i>
                                                         </div>`;
                                    }

                                    var userHtml = `
                                        <div class="user-item" data-user-id="${user.id}" data-user-name="${displayName}" 
                                             style="padding: 10px; border-bottom: 1px solid #eee; cursor: pointer; display: flex; align-items: center; transition: background-color 0.2s;"
                                             onmouseover="this.style.backgroundColor='#f0f8ff'" 
                                             onmouseout="this.style.backgroundColor='transparent'">
                                            ${avatarElement}
                                            <div style="flex: 1;">
                                                <div style="font-weight: bold; color: #333;">${displayName}</div>
                                                <div style="font-size: 12px; color: #666;">${username}${mobile}</div>
                                            </div>
                                            <div style="color: #999;">
                                                <i class="fa fa-hand-pointer-o"></i>
                                            </div>
                                        </div>
                                    `;
                                    $container.append(userHtml);
                                });

                                // 如果有更多数据，添加提示
                                if (data.more) {
                                    $container.append('<div style="padding: 10px; text-align: center; color: #999; font-style: italic; border-top: 1px solid #ddd;"><i class="fa fa-ellipsis-h"></i> 还有更多用户，请使用搜索功能</div>');
                                }

                                // 绑定点击事件
                                $container.find('.user-item').on('click', function () {
                                    var userId = $(this).data('user-id');
                                    var userName = $(this).data('user-name');

                                    // 移除其他选中状态
                                    $container.find('.user-item').css('background-color', 'transparent');
                                    // 设置当前选中状态
                                    $(this).css('background-color', '#e8f5e8');

                                    // 设置选中的用户
                                    $('#selected-user-id').val(userId);
                                    $('#selected-user-text').text(userName);
                                    $('#selected-user-info').show();
                                });

                            } else {
                                var noResultText = keyword ?
                                    '未找到匹配 "' + keyword + '" 的用户' :
                                    '暂无可用用户';
                                $container.html('<div style="padding: 20px; text-align: center; color: #999;"><i class="fa fa-user-times"></i> ' + noResultText + '</div>');
                                if (data.msg) {
                                    console.error('搜索错误:', data.msg);
                                }
                            }
                        },
                        error: function (xhr, status, error) {
                            console.error('请求失败:', error, xhr.responseText);
                            var errorMsg = '加载失败，请点击"搜索"重试';

                            // 检查是否是权限问题
                            if (xhr.responseText && (xhr.responseText.indexOf('authorization') !== -1 || xhr.responseText.indexOf('登录') !== -1)) {
                                errorMsg = '请先登录管理后台';
                                Layer.alert('权限验证失败，请先登录管理后台再使用此功能。', {
                                    icon: 0,
                                    title: '权限提示',
                                    btn: ['去登录', '取消'],
                                    yes: function () {
                                        window.open('/', '_blank');
                                    }
                                });
                            }

                            $container.html('<div style="padding: 20px; text-align: center; color: red;"><i class="fa fa-exclamation-triangle"></i> ' + errorMsg + '</div>');
                        }
                    });
                }

                // 用户搜索功能 - 实时搜索（可选）
                var searchTimer;
                $(document).on('input', '#search-user', function () {
                    var keyword = $(this).val();
                    clearTimeout(searchTimer);

                    // 如果输入为空，不自动搜索，让用户点击"全部"按钮
                    if (keyword.trim() === '') {
                        return;
                    }

                    // 延迟搜索，避免频繁请求
                    searchTimer = setTimeout(function () {
                        loadUsers(keyword);
                    }, 500);
                });
            },

            removeMember: function (ids) {
                Layer.confirm('确定要删除选中的成员吗？', function (index) {
                    $.ajax({
                        url: '/communityclasses/communityclasses/removeClassMember',
                        type: 'POST',
                        data: { ids: ids.join(',') },
                        success: function (data) {
                            if (data.code === 1) {
                                Layer.msg(data.msg, { icon: 1 });
                                $('#members-table').bootstrapTable('refresh');
                            } else {
                                Layer.msg(data.msg, { icon: 2 });
                            }
                            Layer.close(index);
                        }
                    });
                });
            },

            approveMember: function (ids) {
                var memberCount = ids.length;
                var html = `
                    <div style="padding: 20px;">
                        <div class="alert alert-info" style="margin-bottom: 20px;">
                            <i class="fa fa-info-circle"></i> 
                            即将审批 <strong>${memberCount}</strong> 个成员
                        </div>
                        
                        <div class="form-group">
                            <label class="control-label" style="font-weight: bold; margin-bottom: 10px; display: block;">
                                <i class="fa fa-gavel"></i> 审批结果：
                            </label>
                            <select id="approve-status" class="form-control" style="border-radius: 4px; padding: 8px;">
                                <option value="1">✓ 通过 - 成员可正常参与班级活动</option>
                                <option value="2">✗ 拒绝 - 成员申请被拒绝</option>
                            </select>
                        </div>
                        
                        <div class="alert alert-warning" style="margin-top: 15px;">
                            <i class="fa fa-exclamation-triangle"></i> 
                            <strong>注意：</strong>此操作将影响所选成员的班级状态
                        </div>
                    </div>
                `;

                Layer.open({
                    type: 1,
                    title: '<i class="fa fa-gavel"></i> 批量审批成员',
                    content: html,
                    area: ['450px', '300px'],
                    btn: ['<i class="fa fa-check"></i> 确定审批', '<i class="fa fa-times"></i> 取消'],
                    btnAlign: 'c',
                    yes: function (index) {
                        var status = $('#approve-status').val();
                        var statusText = status == 1 ? '通过' : '拒绝';

                        Layer.msg('正在审批...', { icon: 16, shade: 0.3, time: 0 });

                        $.ajax({
                            url: '/communityclasses/communityclasses/approveClassMember',
                            type: 'POST',
                            data: {
                                ids: ids.join(','),
                                status: status
                            },
                            success: function (data) {
                                Layer.closeAll('loading');
                                if (data.code === 1) {
                                    Layer.msg('成功' + statusText + ' ' + memberCount + ' 个成员', {
                                        icon: 1,
                                        time: 2000
                                    });
                                    $('#members-table').bootstrapTable('refresh');
                                    Layer.close(index);
                                } else {
                                    Layer.msg(data.msg || '审批失败', {
                                        icon: 2,
                                        time: 3000
                                    });
                                }
                            },
                            error: function () {
                                Layer.closeAll('loading');
                                Layer.msg('网络错误，请重试', {
                                    icon: 2,
                                    time: 3000
                                });
                            }
                        });
                    }
                });
            },

            editMember: function (row) {
                var currentStatusText = {
                    '0': '待审批',
                    '1': '正常',
                    '2': '已拒绝'
                }[row.status] || '未知';

                var html = `
                    <div style="padding: 20px;">
                        <div class="form-group" style="margin-bottom: 20px;">
                            <label class="control-label" style="font-weight: bold; margin-bottom: 10px; display: block;">
                                <i class="fa fa-user"></i> 用户信息：
                            </label>
                            <div class="well well-sm" style="background-color: #f9f9f9; padding: 15px; border-radius: 4px;">
                                <p style="margin: 0; font-size: 14px;">
                                    <strong>昵称：</strong>${row.nickname || '未设置'}<br>
                                    <strong>用户名：</strong>${row.username || '未知'}<br>
                                    <strong>手机号：</strong>${row.mobile || '未绑定'}<br>
                                    <strong>当前状态：</strong><span class="label label-${row.status == 1 ? 'success' : (row.status == 0 ? 'warning' : 'danger')}">${currentStatusText}</span>
                                </p>
                            </div>
                        </div>
                        
                        <div class="form-group">
                            <label class="control-label" style="font-weight: bold; margin-bottom: 10px; display: block;">
                                <i class="fa fa-flag"></i> 修改状态：
                            </label>
                            <select id="edit-member-status" class="form-control" style="border-radius: 4px; padding: 8px;">
                                <option value="0" ${row.status == 0 ? 'selected' : ''}>⏳ 待审批 - 等待管理员审核</option>
                                <option value="1" ${row.status == 1 ? 'selected' : ''}>✓ 正常 - 可正常参与班级活动</option>
                                <option value="2" ${row.status == 2 ? 'selected' : ''}>✗ 已拒绝 - 申请被拒绝</option>
                            </select>
                        </div>
                        
                        <div class="alert alert-info" style="margin-top: 15px;">
                            <i class="fa fa-lightbulb-o"></i> 
                            <strong>提示：</strong>修改状态后将立即生效
                        </div>
                    </div>
                `;

                Layer.open({
                    type: 1,
                    title: '<i class="fa fa-edit"></i> 编辑成员状态',
                    content: html,
                    area: ['480px', '400px'],
                    btn: ['<i class="fa fa-save"></i> 保存修改', '<i class="fa fa-times"></i> 取消'],
                    btnAlign: 'c',
                    yes: function (index) {
                        var status = $('#edit-member-status').val();
                        var statusText = {
                            '0': '待审批',
                            '1': '正常',
                            '2': '已拒绝'
                        }[status];

                        Layer.msg('正在保存...', { icon: 16, shade: 0.3, time: 0 });

                        $.ajax({
                            url: 'communityclasses/communityclasses/approveClassMember',
                            type: 'POST',
                            data: {
                                ids: row.id,
                                status: status
                            },
                            success: function (data) {
                                Layer.closeAll('loading');
                                if (data.code === 1) {
                                    Layer.msg('成功将用户状态修改为：' + statusText, {
                                        icon: 1,
                                        time: 2000
                                    });
                                    $('#members-table').bootstrapTable('refresh');
                                    Layer.close(index);
                                } else {
                                    Layer.msg(data.msg || '修改失败', {
                                        icon: 2,
                                        time: 3000
                                    });
                                }
                            },
                            error: function () {
                                Layer.closeAll('loading');
                                Layer.msg('网络错误，请重试', {
                                    icon: 2,
                                    time: 3000
                                });
                            }
                        });
                    }
                });
            },

            exportMembers: function (classId) {
                Layer.confirm('确定要导出班级成员列表吗？', {
                    icon: 3,
                    title: '导出确认'
                }, function (index) {
                    Layer.msg('正在生成导出文件...', { icon: 16, time: 0 });

                    // 创建一个隐藏的表单来提交导出请求
                    var form = $('<form method="post" action="admin/communityclasses/communityclasses/exportClassMembers"></form>');
                    form.append('<input type="hidden" name="class_id" value="' + classId + '">');
                    $('body').append(form);
                    form.submit();
                    form.remove();

                    Layer.closeAll('loading');
                    Layer.close(index);
                    Layer.msg('导出请求已提交', { icon: 1, time: 2000 });
                });
            },

            updateMemberStats: function (data) {
                var total = data.total || 0;
                var normal = 0;
                var pending = 0;
                var rejected = 0;

                if (data.rows && data.rows.length > 0) {
                    data.rows.forEach(function (member) {
                        switch (member.status) {
                            case '1':
                            case 1:
                                normal++;
                                break;
                            case '0':
                            case 0:
                                pending++;
                                break;
                            case '2':
                            case 2:
                                rejected++;
                                break;
                        }
                    });
                }

                // 更新统计显示
                $('#total-members').text(total);
                $('#normal-members').text(normal);
                $('#pending-members').text(pending);
                $('#rejected-members').text(rejected);
            },

            initManagerSelection: function () {
                // 显示当前管理员信息
                Controller.api.displayCurrentManager();
                
                // 绑定选择管理员按钮事件
                $('#btn-choose-manager').on('click', function () {
                    Controller.api.showManagerSelectionDialog();
                });
                
                // 绑定清空管理员按钮事件
                $('#btn-clear-manager').on('click', function () {
                    $('#c-manager_id2').val('');
                    $('#manager-info').show();
                    $('#manager-name').text('');
                    $('#manager-avatar').attr('src', '').hide();
                    $('#manager-avatar-fallback').show();
                });

                // 绑定内联选择管理员按钮事件
                $('#btn-choose-manager-inline').on('click', function () {
                    console.log('内联选择管理员按钮被点击');
                    try {
                        Controller.api.showManagerSelectionDialog();
                    } catch (e) {
                        console.error('调用showManagerSelectionDialog失败:', e);
                    }
                });

                // 绑定内联清空管理员按钮事件
                $('#btn-clear-manager-inline').on('click', function () {
                    $('#c-manager_id2').val('');
                    $('#manager-info').show();
                    $('#manager-name').text('');
                    $('#manager-avatar').attr('src', '').hide();
                    $('#manager-avatar-fallback').show();
                });
            },

            displayCurrentManager: function () {
                var managerId = $('#c-manager_id2').val();
                if (managerId && managerId > 0) {
                    // 获取管理员信息
                    $.ajax({
                        url: '/communityclasses/communityclasses/getAdminInfo',
                        type: 'GET',
                        data: { id: managerId },
                        success: function (data) {
                            if (data.code === 1 && data.data) {
                                $('#manager-name').text(data.data.nickname || data.data.username || '未知用户');
                                
                                // 显示头像
                                if (data.data.avatar) {
                                    $('#manager-avatar').attr('src', data.data.avatar).show();
                                    $('#manager-avatar-fallback').hide();
                                } else {
                                    $('#manager-avatar').hide();
                                    $('#manager-avatar-fallback').show();
                                }
                                
                                $('#manager-info').show();
                            }
                        }
                    });
                }
            },

            showManagerSelectionDialog: function () {
                console.log('showManagerSelectionDialog 被调用');
                var html = `
                    <div style="padding: 20px;">
                        <div class="form-group" style="margin-bottom: 20px;">
                            <label class="control-label" style="font-weight: bold; margin-bottom: 8px; display: block;">
                                <i class="fa fa-search"></i> 搜索用户（作为班级管理员）：
                            </label>
                            <div class="input-group">
                                <input type="text" id="search-admin" class="form-control" 
                                       placeholder="输入用户昵称、用户名或手机号进行搜索" 
                                       style="border-radius: 4px 0 0 4px;">
                                <span class="input-group-btn">
                                    <button type="button" id="btn-search-admin" class="btn btn-primary" 
                                            style="border-radius: 0 4px 4px 0;">
                                        <i class="fa fa-search"></i> 搜索
                                    </button>
                                    <button type="button" id="btn-load-all-admins" class="btn btn-default" 
                                            title="显示所有管理员">
                                        <i class="fa fa-list"></i> 全部
                                    </button>
                                </span>
                            </div>
                            <small class="help-block text-muted">
                                <i class="fa fa-info-circle"></i> 提示：留空搜索框点击"全部"可显示所有用户
                            </small>
                        </div>
                        
                        <div class="form-group" style="margin-bottom: 20px;">
                            <label class="control-label" style="font-weight: bold; margin-bottom: 8px; display: block;">
                                <i class="fa fa-user"></i> 选择用户作为班级管理员：
                            </label>
                            <div id="admin-list-container" style="max-height: 250px; overflow-y: auto; border: 1px solid #ddd; border-radius: 4px; background: #f9f9f9;">
                                <div id="admin-loading" style="padding: 20px; text-align: center; color: #999;">
                                    <i class="fa fa-spinner fa-spin"></i> 正在加载管理员列表...
                                </div>
                            </div>
                            <input type="hidden" id="selected-admin-id" value="">
                            <div id="selected-admin-info" style="margin-top: 8px; padding: 8px; background: #e8f5e8; border-radius: 4px; display: none;">
                                <strong>已选择：</strong><span id="selected-admin-text"></span>
                            </div>
                            <small class="help-block text-muted">
                                <i class="fa fa-info-circle"></i> 点击用户头像或名称进行选择
                            </small>
                        </div>
                        
                        <div class="alert alert-info" style="margin-top: 15px; padding: 10px; border-radius: 4px;">
                            <i class="fa fa-lightbulb-o"></i> 
                            <strong>操作提示：</strong>选择用户后点击确定即可设置为班级管理员
                        </div>
                    </div>
                `;

                Layer.open({
                    type: 1,
                    title: '<i class="fa fa-user-plus"></i> 选择班级管理员（从用户中选择）',
                    content: html,
                    area: ['600px', '520px'],
                    btn: ['<i class="fa fa-check"></i> 确定选择', '<i class="fa fa-times"></i> 取消'],
                    btnAlign: 'c',
                    success: function (layero, index) {
                        // 对话框显示成功后立即加载管理员列表
                        setTimeout(function () {
                            loadAdmins('');
                        }, 100);

                        // 绑定搜索按钮事件
                        $('#btn-search-admin').on('click', function () {
                            var keyword = $('#search-admin').val().trim();
                            loadAdmins(keyword);
                        });

                        // 绑定显示全部按钮事件
                        $('#btn-load-all-admins').on('click', function () {
                            $('#search-admin').val('');
                            loadAdmins('');
                        });

                        // 绑定回车搜索
                        $('#search-admin').on('keypress', function (e) {
                            if (e.which === 13) {
                                var keyword = $(this).val().trim();
                                loadAdmins(keyword);
                            }
                        });
                    },
                    yes: function (index, layero) {
                        var adminId = $('#selected-admin-id').val();
                        var adminText = $('#selected-admin-text').text();

                        if (!adminId) {
                            Layer.msg('请先选择用户', {
                                icon: 0,
                                time: 2000,
                                shade: 0.3
                            });
                            return false;
                        }

                        // 设置选中的管理员
                        $('#c-manager_id2').val(adminId);
                        $('#manager-name').text(adminText);
                        
                        // 设置头像 - 从全局变量中查找选中的管理员信息
                        var selectedAdmin = null;
                        if (window.currentAdminList && window.currentAdminList.length > 0) {
                            selectedAdmin = window.currentAdminList.find(function(admin) { return admin.id == adminId; });
                        }
                        
                        if (selectedAdmin && selectedAdmin.avatar) {
                            // 构建完整的头像URL
                            var avatarUrl = selectedAdmin.avatar;
                            if (avatarUrl && !avatarUrl.startsWith('http') && !avatarUrl.startsWith('/')) {
                                avatarUrl = '/' + avatarUrl;
                            }
                            $('#manager-avatar').attr('src', avatarUrl).show();
                            $('#manager-avatar-fallback').hide();
                        } else {
                            $('#manager-avatar').hide();
                            $('#manager-avatar-fallback').show();
                        }
                        
                        $('#manager-info').show();
                        
                        Layer.msg('成功选择用户：' + adminText, {
                            icon: 1,
                            time: 2000
                        });
                        
                        Layer.close(index);
                        return false;
                    }
                });

                // 加载管理员列表的函数
                function loadAdmins(keyword) {
                    keyword = keyword || '';

                    var $container = $('#admin-list-container');
                    $container.html('<div style="padding: 20px; text-align: center; color: #999;"><i class="fa fa-spinner fa-spin"></i> 正在搜索用户...</div>');

                    $.ajax({
                        url: '/communityclasses/communityclasses/getUserAdminList',
                        type: 'GET',
                        data: { q: keyword },
                        success: function (data) {
                            $container.empty();

                            // 保存管理员列表到全局变量，供选择头像使用
                            if (data.code === 1 && data.data) {
                                window.currentAdminList = data.data;
                            }

                            if (data.code === 1 && data.data && data.data.length > 0) {
                                // 添加提示信息
                                var tipText = keyword ?
                                    '搜索到 ' + data.data.length + ' 个用户' :
                                    '共 ' + data.data.length + ' 个用户';
                                $container.append('<div style="padding: 8px; background: #e8f4fd; border-bottom: 1px solid #ddd; font-size: 12px; color: #666;"><i class="fa fa-info-circle"></i> ' + tipText + '</div>');

                                // 添加管理员列表
                                $.each(data.data, function (index, admin) {
                                    var displayName = admin.nickname || admin.username || '未知用户';
                                    var avatarHtml = '';
                                    
                                    // 构建完整的头像URL
                                    var avatarUrl = admin.avatar || '';
                                    if (avatarUrl && !avatarUrl.startsWith('http') && !avatarUrl.startsWith('/')) {
                                        avatarUrl = '/' + avatarUrl;
                                    }
                                    if (!avatarUrl) {
                                        avatarUrl = '/assets/img/avatar.png';
                                    }
                                    
                                    if (avatarUrl && avatarUrl !== '/assets/img/avatar.png') {
                                        avatarHtml = `<img src="${avatarUrl}" style="width: 32px; height: 32px; border-radius: 50%; object-fit: cover;" onerror="this.style.display='none'; this.nextElementSibling.style.display='block';"><i class="fa fa-user-circle" style="font-size: 24px; color: #337ab7; display: none;"></i>`;
                                    } else {
                                        avatarHtml = '<i class="fa fa-user-circle" style="font-size: 24px; color: #337ab7;"></i>';
                                    }
                                    var adminHtml = `
                                        <div class="admin-item" data-admin-id="${admin.id}" data-admin-name="${displayName}" 
                                             style="padding: 12px; border-bottom: 1px solid #eee; cursor: pointer; transition: background-color 0.2s;">
                                            <div style="display: flex; align-items: center;">
                                                <div style="margin-right: 12px;">
                                                    ${avatarHtml}
                                                </div>
                                                <div style="flex: 1;">
                                                    <div style="font-weight: bold; color: #333; margin-bottom: 4px;">${displayName}</div>
                                                    <div style="color: #666; font-size: 12px;">
                                                        <i class="fa fa-user"></i> 用户名: ${admin.username || '未知'}
                                                        <i class="fa fa-tag" style="margin-left: 10px;"></i> ID: ${admin.id}
                                                    </div>
                                                </div>
                                                <div style="color: #999;">
                                                    <i class="fa fa-hand-pointer-o"></i>
                                                </div>
                                            </div>
                                        </div>
                                    `;
                                    $container.append(adminHtml);
                                });

                                // 绑定点击事件
                                $container.find('.admin-item').on('click', function () {
                                    var adminId = $(this).data('admin-id');
                                    var adminName = $(this).data('admin-name');

                                    // 移除其他选中状态
                                    $container.find('.admin-item').css('background-color', 'transparent');
                                    // 设置当前选中状态
                                    $(this).css('background-color', '#e8f5e8');

                                    // 设置选中的管理员
                                    $('#selected-admin-id').val(adminId);
                                    $('#selected-admin-text').text(adminName);
                                    $('#selected-admin-info').show();
                                });

                            } else {
                                var noResultText = keyword ?
                                    '未找到匹配 "' + keyword + '" 的用户' :
                                    '暂无可用用户';
                                $container.html('<div style="padding: 20px; text-align: center; color: #999;"><i class="fa fa-user-times"></i> ' + noResultText + '</div>');
                                if (data.msg) {
                                    console.error('搜索错误:', data.msg);
                                }
                            }
                        },
                        error: function (xhr, status, error) {
                            console.error('请求失败:', error, xhr.responseText);
                            var errorMsg = '加载失败，请点击"搜索"重试';

                            // 检查是否是权限问题
                            if (xhr.responseText && (xhr.responseText.indexOf('authorization') !== -1 || xhr.responseText.indexOf('登录') !== -1)) {
                                errorMsg = '请先登录管理后台';
                                Layer.alert('权限验证失败，请先登录管理后台再使用此功能。', {
                                    icon: 0,
                                    title: '权限提示',
                                    btn: ['去登录', '取消'],
                                    yes: function () {
                                        window.open('/', '_blank');
                                    }
                                });
                            }

                            $container.html('<div style="padding: 20px; text-align: center; color: red;"><i class="fa fa-exclamation-triangle"></i> ' + errorMsg + '</div>');
                        }
                    });
                }

                // 管理员搜索功能 - 实时搜索（可选）
                var searchTimer;
                $(document).on('input', '#search-admin', function () {
                    var keyword = $(this).val();
                    clearTimeout(searchTimer);

                    // 如果输入为空，不自动搜索，让用户点击"全部"按钮
                    if (keyword.trim() === '') {
                        return;
                    }

                    // 延迟搜索，避免频繁请求
                    searchTimer = setTimeout(function () {
                        loadAdmins(keyword);
                    }, 500);
                });
            }
        }
    };
    return Controller;
});